import 'dart:convert';

import 'package:dio/dio.dart';

class CurlUtil {
  static String generateCurl(RequestOptions options) {
    const String curl = 'curl -X ';
    final String method = options.method;
    String url = options.baseUrl + options.path;
    String query = '';

    if (options.data != null && options.data is String) {
      query = options.data;
    } else {
      late Map<String, dynamic> map;

      if (options.queryParameters.isNotEmpty) {
        map = options.queryParameters;
      } else if (options.data is Map) {
        map = options.data;
      } else if (options.data is String) {
      } else if (options.data is FormData) {
        map = {};
        map.addEntries((options.data as FormData).fields);
      } else {
        map = {};
      }
      query = Transformer.urlEncodeMap(map);
    }
    String curlUrl;
    if (method.toLowerCase() == 'get') {
      if (query.isNotEmpty) {
        url += (url.contains('?') ? '&' : '?') + query;
      }
      String header = '';
      options.headers.forEach((key, value) {
        if (key != 'content-length') {
          header += ' -H ' '\"$key:$value\" ';
        }
      });

      curlUrl = '$curl$method $header \"$url\"';
    } else {
      String header = '';
      options.headers.forEach((key, value) {
        if (key != 'content-length') {
          header += ' -H ' '\"$key:$value\" ';
        }
      });
      final param = json.encode(options.data).replaceAll('"', '\\"');
      header += " -d \"$param\"";
      curlUrl = '$curl$method $header \"$url\"';
    }

    return curlUrl;
  }
}
